<template>
  <div class="user-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button type="primary" @click="$router.push('/user/add')">
            添加用户
          </el-button>
        </div>
      </template>
      
      <!-- 搜索筛选 -->
      <div class="search-section">
        <el-form :model="searchForm" inline>
          <el-form-item label="用户名">
            <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="searchForm.realName" placeholder="请输入姓名" clearable />
          </el-form-item>
          <el-form-item label="角色">
            <el-select v-model="searchForm.role" placeholder="请选择角色" clearable>
              <el-option label="管理员" value="admin"></el-option>
              <el-option label="操作员" value="operator"></el-option>
              <el-option label="查看者" value="viewer"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="启用" value="active"></el-option>
              <el-option label="禁用" value="inactive"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 数据表格 -->
      <el-table 
        :data="tableData" 
        border 
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        size="small"
      >
        <el-table-column type="selection" width="45" />
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="username" label="用户名" width="100" />
        <el-table-column prop="realName" label="姓名" width="80" />
        <el-table-column prop="email" label="邮箱" width="140" show-overflow-tooltip />
        <el-table-column prop="phone" label="电话" width="110" />
        <el-table-column prop="roleNames" label="角色" width="120" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'" size="small">
              {{ scope.row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="department" label="部门" width="100" show-overflow-tooltip />
        <el-table-column prop="lastLoginTime" label="最后登录" width="130" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="130" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <div class="table-actions">
              <el-button 
                type="text" 
                size="small" 
                @click="viewUser(scope.row)"
              >
                查看
              </el-button>
              <el-button 
                type="text" 
                size="small" 
                @click="editUser(scope.row)"
              >
                编辑
              </el-button>
              <el-button 
                type="text" 
                size="small" 
                @click="resetPassword(scope.row)"
              >
                重置密码
              </el-button>
              <el-button 
                type="text" 
                size="small" 
                @click="toggleStatus(scope.row)"
              >
                {{ scope.row.status === 'active' ? '禁用' : '启用' }}
              </el-button>
              <el-button 
                type="text" 
                size="small" 
                @click="handleDeleteUser(scope.row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      
      <!-- 批量操作 -->
      <div class="batch-actions" v-if="selectedRows.length > 0">
        <el-button @click="batchDelete">批量删除</el-button>
        <el-button @click="batchEnable">批量启用</el-button>
        <el-button @click="batchDisable">批量禁用</el-button>
      </div>
    </el-card>
    
    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="用户详情"
      width="600px"
    >
      <div v-if="currentUser" class="user-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户ID">{{ currentUser.id }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ currentUser.username }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{ currentUser.realName }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ currentUser.email }}</el-descriptions-item>
          <el-descriptions-item label="电话">{{ currentUser.phone }}</el-descriptions-item>
          <el-descriptions-item label="角色">
            <el-tag :type="getRoleTagType(currentUser.role)" size="small">
              {{ getRoleName(currentUser.role) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentUser.status === 'active' ? 'success' : 'danger'">
              {{ currentUser.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="部门">{{ currentUser.department }}</el-descriptions-item>
          <el-descriptions-item label="最后登录">{{ currentUser.lastLoginTime }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentUser.createTime }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { userApi } from '@/api'

const router = useRouter()
const loading = ref(false)
const detailVisible = ref(false)
const currentUser = ref<{ id: number; username: string; realName: string; email: string; phone: string; role: string; status: string; department: string; lastLoginTime: string; createTime: string } | null>(null)
const selectedRows = ref<any[]>([])

// 搜索表单
const searchForm = ref({
  username: '',
  realName: '',
  role: '',
  status: ''
})

// 分页
const pagination = ref({
  current: 1,
  size: 20,
  total: 0
})

// 表格数据
const users = ref<{ id: number; username: string; realName: string; email: string; phone: string; role: string; status: string; department: string; lastLoginTime: string; createTime: string }[]>([])
const tableData = ref<any[]>([])

const getRoleTagType = (role: string) => {
  const roleMap: Record<string, string> = {
    'admin': 'danger',
    'operator': 'warning',
    'viewer': 'info'
  }
  return roleMap[role] || 'info'
}

const getRoleName = (role: string) => {
  const roleMap: Record<string, string> = {
    'admin': '管理员',
    'operator': '操作员',
    'viewer': '查看者'
  }
  return roleMap[role] || role
}

const handleSearch = () => {
  pagination.value.current = 1
  loadData()
}

const resetSearch = () => {
  searchForm.value = {
    username: '',
    realName: '',
    role: '',
    status: ''
  }
  handleSearch()
}

const loadData = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pagination.value.current,
      size: pagination.value.size,
      username: searchForm.value.username,
      fullName: searchForm.value.realName,
      status: searchForm.value.status ? (searchForm.value.status === 'active' ? 1 : 0) : undefined
    }

    const res: any = await userApi.getList(params)
    const rows = res.list || res.records || []
    tableData.value = rows.map((u:any)=>({
      ...u,
      realName: u.fullName,
      phone: u.phone ?? '-',
      department: u.department ?? '-',
      lastLoginTime: u.lastLoginAt ? u.lastLoginAt.replace('T',' ').split('.')[0] : '-',
      createTime: u.createdAt ? (u.createdAt.split('T')[0] + ' ' + u.createdAt.split('T')[1]?.split('.')[0]) : '-',
      status: u.status === 1 ? 'active' : 'inactive',
      role: u.role || '',
      roleNames: u.roleNames || '' // Assuming roleNames is available in the API response
    }))
    pagination.value.total = res.total || 0
  } finally {
    loading.value = false
  }
}

const handleSizeChange = (size: number) => {
  pagination.value.size = size
  loadData()
}

const handleCurrentChange = (current: number) => {
  pagination.value.current = current
  loadData()
}

const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

const viewUser = (row: any) => {
  currentUser.value = row
  detailVisible.value = true
}

const editUser = (row: any) => {
  router.push(`/user/edit/${row.id}`)
}

const resetPassword = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要重置用户"${row.realName}"的密码吗？`,
      '确认重置',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟API调用
    ElMessage.success('密码重置成功，新密码已发送到用户邮箱')
  } catch {
    // 用户取消
  }
}

const toggleStatus = async (row: any) => {
  const action = row.status === 'active' ? '禁用' : '启用'
  try {
    await ElMessageBox.confirm(
      `确定要${action}用户"${row.realName}"吗？`,
      `确认${action}`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 后端接口 updateStatus 需要数值，约定：1=active, 0=inactive
    const newStatusCode = row.status === 'active' ? 0 : 1
    await userApi.updateStatus(row.id, newStatusCode)
    row.status = newStatusCode === 1 ? 'active' : 'inactive'
    ElMessage.success(`${action}成功`)
  } catch {
    // 用户取消
  }
}

const handleDeleteUser = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户"${row.realName}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await userApi.delete(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch {
    // 用户取消删除
  }
}

const batchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的用户')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 个用户吗？`,
      '批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await userApi.batchDelete(selectedRows.value.map(u => u.id))
    ElMessage.success('批量删除成功')
    selectedRows.value = []
    loadData()
  } catch {
    // 用户取消
  }
}

const batchEnable = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要启用的用户')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要启用选中的 ${selectedRows.value.length} 个用户吗？`,
      '批量启用',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    await Promise.all(selectedRows.value.map(u => userApi.updateStatus(u.id, 1)))
    ElMessage.success('批量启用成功')
    loadData()
  } catch {
    // 用户取消
  }
}

const batchDisable = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要禁用的用户')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要禁用选中的 ${selectedRows.value.length} 个用户吗？`,
      '批量禁用',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await Promise.all(selectedRows.value.map(u => userApi.updateStatus(u.id, 0)))
    ElMessage.success('批量禁用成功')
    loadData()
  } catch {
    // 用户取消
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.user-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.batch-actions {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
  display: flex;
  gap: 10px;
}

.user-detail {
  padding: 20px 0;
}

/* 表格操作按钮样式优化 */
.table-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.table-actions .el-button {
  padding: 4px 8px;
  font-size: 12px;
  min-width: auto;
}

/* 表格响应式优化 */
@media (max-width: 1200px) {
  .table-actions {
    flex-direction: column;
    gap: 2px;
  }
  
  .table-actions .el-button {
    padding: 2px 4px;
    font-size: 11px;
  }
}

@media (max-width: 768px) {
  .user-list {
    padding: 10px;
  }
  
  .search-section {
    padding: 15px;
  }
  
  .search-section .el-form {
    display: flex;
    flex-direction: column;
  }
  
  .search-section .el-form-item {
    margin-bottom: 10px;
  }
  
  .batch-actions {
    flex-direction: column;
  }
  
  /* 移动端表格优化 */
  :deep(.el-table) {
    font-size: 12px;
  }
  
  :deep(.el-table th),
  :deep(.el-table td) {
    padding: 8px 4px;
  }
}
</style> 